package com.javafactroy.kunlong.bip.icp.message.data.netty.codec;

import com.javafactroy.kunlong.bip.icp.message.data.base.AppMsg;
import com.javafactroy.kunlong.bip.icp.message.data.iface.AppBase;
import com.javafactroy.kunlong.bip.icp.message.dxp.base.DxpHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;

import java.util.List;
//no user
public class AppSelfMsgDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readableBytes()> AppBase.MAX_FRAME_LENGTH){
            throw new TooLongFrameException();
        }
        if (byteBuf.readableBytes() >= DxpHeader.MSG_HEADER_LEN) {
            AppMsg appMessage = new AppMsg();
            byte[] bytes = new byte[DxpHeader.MSG_HEADER_LEN];
            byteBuf.readBytes(bytes);
            appMessage.getAppHeader().decode(bytes);
            int ilen = appMessage.getAppHeader().getMsgLen()- bytes.length;
            if (byteBuf.readableBytes() >=ilen) {
                bytes = new byte[ilen];
                byteBuf.readBytes(bytes);
                //appMessage.getAppBody().decode(bytes);
                System.out.println(appMessage);
                list.add(appMessage);
            }
        }
    }
}
